package org.example.ims.Service.Base.Impl;



import org.example.ims.Entity.Base.Supplier;
import org.example.ims.Repository.Base.SupplierRepository;
import org.example.ims.Service.Base.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service("supplierService")
public class SupplierServiceImpl implements SupplierService {

    private final SupplierRepository supplierRepository;

    @Autowired
    public SupplierServiceImpl(SupplierRepository supplierRepository) {
        this.supplierRepository = supplierRepository;
    }

    @Override
    // 创建供货商
    public Supplier createSupplier(Supplier supplier) {
        return supplierRepository.save(supplier);
    }

    @Override
    public Page<Supplier> getAllSuppliers(Integer page, Integer size) {
        return supplierRepository.findAll(PageRequest.of(page, size));
    }

    @Override
    // 根据ID获取供货商
    public Optional<Supplier> getSupplierById(Integer id) {
        return supplierRepository.findById(id);
    }
    
    @Override
    public Supplier getSupplierByName(String name) {
        return supplierRepository.findBySupplierName(name);
    }

    @Override
    public Page<Supplier> searchSuppliers(String name, String contact, String phone, Integer page, Integer size) {
        return supplierRepository.searchSuppliers(
                name, contact, phone ,PageRequest.of(page, size)
        );
    }

    @Override
    // 更新供货商信息
    public Supplier updateSupplier(Integer id, Supplier supplierDetails) {
        Optional<Supplier> supplier = supplierRepository.findById(id);
        if (supplier.isPresent()) {
            Supplier _supplier = supplier.get();
            supplierDetails.setSupplierId(_supplier.getSupplierId());
            return supplierRepository.save(supplierDetails);
        }
        return null;
    }

    @Override
    // 删除供货商
    public void deleteSupplier(Integer id) {
        if (!supplierRepository.existsById(id)) {
            throw new RuntimeException("Supplier does not exist");
        }
        supplierRepository.deleteById(id);
    }
}